<template>
  <div class="user-header">
    <el-button type="primary" @click="handleAdd()">+ 新增</el-button>
    <el-form :inline="true" :model="formInline">
      <el-form-item label="请输入">
        <el-input
          @blur="Handleblur"
          v-model="formInline.keyword"
          placeholder="请输入用户名"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="table">
    <el-table :data="list" style="width: 100%" height="500px ">
      <el-table-column
        v-for="item in tableLabel"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        :width="item.width ? item.width : 120"
      />
      <el-table-column fixed="right" label="操作" min-width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="handledelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      small
      background
      layout="prev, pager, next"
      :total="config.total"
      class="mt-4 pager"
      @current-change="changePage"
    />
  </div>
  <el-dialog
    v-model="dialogVisible"
    :title="action == 'add' ? '新增用户' : '编辑用户'"
    :before-close="handleClose"
    width="50%"
  >
    <el-form
      :inline="true"
      :rules="rules"
      :model="form"
      ref="userform"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名:" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="年龄:" prop="age">
            <el-input v-model="form.age" placeholder="请输入年龄"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="性别" prop="sex">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birth">
            <el-date-picker
              type="date"
              label="出生日期"
              placeholder="选择日期"
              v-model="form.birth"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-form-item label="地址:" prop="addr">
          <el-input v-model="form.addr" placeholder="请输入地址"></el-input>
        </el-form-item>
      </el-row>
      <el-row style="justify-content: flex-end">
        <el-form-item>
          <el-button type="primary" @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="onSubmit">确定</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import {
  defineComponent,
  onMounted,
  getCurrentInstance,
  ref,
  reactive,
} from 'vue'

export default defineComponent({
  setup() {
    const { proxy } = getCurrentInstance()
    const list = ref([])
    const config = reactive({
      total: 0,
      page: 1,
      name: '',
    })
    // 输入
    const formInline = reactive({
      keyword: '',
    })
    // 搜索方法
    const handleSearch = () => {
      config.name = formInline.keyword
      getUserData(config)
      formInline.keyword = ''
    }
    // 显示隐藏表单
    const dialogVisible = ref(false)
    const handleClose = (done) => {
      ElMessageBox.confirm('确定关闭吗?')
        .then(() => {
          done()
        })
        .catch(() => {
          // catch error
        })
    }
    const form = reactive({
      name: '',
      age: '',
      sex: '',
      birth: '',
      addr: '',
    })
    const rules = ref({
      name: [{ required: true, message: '请输入姓名' }],
      age: [{ required: true, message: '请输入年龄' }],
      sex: [{ required: true, message: '请输入性别' }],
      birth: [{ required: true, message: '请输入生日' }],
      addr: [{ required: true, message: '请输入地址' }],
    })
    // 日期转换
    const timeFormat = (time) => {
      var time = new Date(time)
      var year = time.getFullYear()
      var month = time.getMonth() + 1
      var date = time.getDate()
      function add(m) {
        return m < 10 ? '0' + m : m
      }
      return year + '-' + add(month) + '-' + add(date)
    }
    // 添加用户
    const onSubmit = () => {
      proxy.$refs.userform.validate(async (valid) => {
        if (valid) {
          if (action.value == 'add') {
            form.birth = timeFormat(form.birth)
            let res = await proxy.$api.addUser(form)
            if (res) {
              dialogVisible.value = false
              proxy.$refs.userform.resetFields()
              getUserData(config)
            }
          } else {
            // 编辑接口
            form.sex == '男' ? (form.sexLabel = 1) : (form.sexLabel = 0)
            form.birth = timeFormat(form.birth)

            let res = await proxy.$api.editUser(form)
            if (res) {
              dialogVisible.value = false
              proxy.$refs.userform.resetFields()
              getUserData(config)
            }
          }
        } else {
          ElMessage({
            showClose: true,
            message: '请输入正确的内容',
            type: 'error',
          })
        }
      })
    }
    // 取消方法
    const handleCancel = () => {
      dialogVisible.value = false
      proxy.$refs.userform.resetFields()
    }
    const tableLabel = reactive([
      {
        prop: 'name',
        label: '姓名',
      },
      {
        prop: 'age',
        label: '年龄',
      },
      {
        prop: 'sexLabel',
        label: '性别',
      },
      {
        prop: 'birth',
        label: '出生日期',
        width: 200,
      },
      {
        prop: 'addr',
        label: '地址',
        width: 320,
      },
    ])
    onMounted(() => {
      getUserData(config)
    })
    // 获取用户数据
    const getUserData = async (config) => {
      let res = await proxy.$api.getUserData(config)
      config.total = res.count
      list.value = res.list.map((item) => {
        item.sexLabel = item.sex == 0 ? '女' : '男'
        return item
      })
      console.log(list.value)
    }
    // 分页改变
    const changePage = (page) => {
      config.page = page
      getUserData(config)
    }
    // 区分编辑还是新增
    const action = ref('add')
    // 新增方法
    const handleAdd = () => {
      dialogVisible.value = true
    }
    // 编辑用户
    const handleEdit = (row) => {
      console.log(row)
      ;(action.value = 'edit'), (dialogVisible.value = true)
      row.sex == 1 ? (row.sex = '男') : (row.sex = '女')
      proxy.$nextTick(() => {
        Object.assign(form, row)
      })
    }
    // 删除方法
    const handledelete = (row) => {
      ElMessageBox.confirm('你确定删除吗')
        .then(async () => {
          await proxy.$api.deleteUser({
            id: row.id,
          })
          ElMessage({
            showClose: true,
            message: '删除成功',
            type: 'success',
          })
          getUserData(config)
        })
        .catch(() => {})
    }
    // 失去焦点触发方法
    const Handleblur = () => {
      getUserData(config)
      console.log(1)
    }
    return {
      list,
      tableLabel,
      config,
      changePage,
      formInline,
      handleSearch,
      dialogVisible,
      handleClose,
      form,
      rules,
      onSubmit,
      handleCancel,
      action,
      handleAdd,
      handleEdit,
      handledelete,
      Handleblur,
    }
  },
})
</script>
<style lang="less" scoped>
.table {
  position: relative;
  height: 520px;
  .pager {
    position: absolute;
    right: 0;
    bottom: -20px;
  }
}
.user-header {
  display: flex;
  justify-content: space-between;
}
</style>
